<?php
/**
 * Controller pre admin-log
 * @author Tomas Srna
 * @package bakalarka
 */

class AdminLogController extends Controller 
{
	protected $resource = 'admin-log';
	
	/**
	 * Akcia index
	 */
	public function index()
	{
		$t = Template::instance();
		
		$dv = new DynamicView();
		$dv->buttonAdd = false;
		$dv->primaryKeys = array('id');
		$dv->baseUrl = APPBASE."admin/log";
		
		$dv->itemCount = Selector::select("count(*) as c")->from('log')
			->fetch()->current()->c;
		
		$t->dv = $dv;
		$t->dvw = new DynamicViewWriter($t->dv, $t);
		
		$t->title = L::selected()->syslog;
		$t->text = "";
		
		$t->render('dynamic-view');
	}
	
	/**
	 * Akcia data
	 */
	public function data()
	{
		$params = $_GET;
		
		$t = Template::instance();
		
		// Kontrola vstupov
		$by_possible = array("id", "date", "user", "type", "message");
		
		$dt = new DynamicTable();
		
		$dt->buttons = NULL;
		
		$dt->itemCount = Selector::select("count(*) as c")->from('log')
			->fetch()->current()->c;
		
		if(!$dt->check($params, $by_possible))
			$t->error = L::selected()->invalidInput;
		
		if(!property_exists($t, 'error'))
		{
			$dt->headers['id'] = L::selected()->id;
			$dt->headers['date'] = L::selected()->date;
			$dt->headers['user'] = L::selected()->user;
			$dt->headers['type'] = L::selected()->type;
			$dt->headers['message'] = L::selected()->message;
			
			$dt->writers['message'] = new LogMessageWriter();
			
			$dt->passwd = false;
			$dt->edit = false;
			$dt->delete = false;
			
			if(!array_key_exists('page', $params))
				$params['page'] = 1;
			
			$select = Selector::select()
						->from(LogModel::struct())
						->limit(($params['page']-1)*Config::$itemsPerPage, 
							Config::$itemsPerPage);
			
			if(array_key_exists('by', $params))
			{
				$order = '`'.$params['by'].'`';
				if(array_key_exists('order', $params))
					$order .= ' '.$params['order'];
				$select->order($order);
			}
			else
			{
				$select->order("`date` desc");
			}
	
			
			$dt->data = $select->fetch();
			
			$t->dtw = new DynamicTableWriter($dt, $t);
		}
	
		$t->dt = $dt;
		$t->render('dynamic-table');
	}
}
